//
//  BK_Calendar_Tool.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/2/27.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_Calendar_Tool.h"
#import "BK_OD_Color.h"
#import "BK_OD_Tool.h"
@implementation BK_Calendar_Tool
/*
接口名称：	thsalebetweenDays
接口用途：	查询日历可卖日期区间
method：	POST
接口地址：	thsalebetweenDays
输入参数：
key	参数类型	是否必须	参数解释
reserveId	string	是	库存id
返回数据：
{
    "success": "true/false //成功/失败",
    "msg": "xxx //返回消息",
    "errorCode": "//",
    "errorMsg": "//",
    "data":
    {
        "fristthDay": "xxxx//2016-07-18",
        "lastthDay": "xxx//2016-09-08",
    }
}
备注：
请求参数：
reserveId:xxx//库存id
*/

/*
    {
        "fristthDay": "2017-02-27",
        "data": {
            "fristthDay": "2017-02-27",
            "lastthDay": "2017-03-25"
        },
        "errorMsg": "",
        "success": true,
        "msg": "",
        "lastthDay": "2017-03-25",
        "errorCode": ""
    }
 */

+(void)BK_Calendar_ThsalebetweenDays:(BK_Calendar_Callback)CallBack WithReserveId:(NSString *)reserveId{
    kOrderLoading;
    NSString *const ODScopeOfMonthURL = @"thsalebetweenDays";
    
    NSString *url = [kOrderURL(ODScopeOfMonthURL) stringByAppendingString:[NSString stringWithFormat:@"?reserveId=%@",reserveId]];
    
    [[RequestManager manager] bkDataRequest:RequestMethodGet URLString:url parameters:nil success:^(id  _Nullable responseObject) {
        BOOL success = [responseObject[@"success"] boolValue];
        if (responseObject == nil || success == NO) {
            kOrderDismiss;
            kOrderPromptMsg(responseObject[@"msg"]);
            return;
        }else{
            kOrderDismiss;
            CallBack(YES, responseObject,nil);
        }
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        kOrderDismiss;
//        NSString *errorMsg;
//        if (error.code == -1001) {
//            errorMsg = @"请求超时";
//        }else if(error.code == 502){
//            errorMsg = @"服务器开小差了，请稍后再试！";
//        }else{
//            errorMsg = @"请求失败";
//        }
//        kOrderPromptMsg(errorMsg);
        CallBack(NO, nil,error);
    }];

}


/*
接口名称：	listCalendar
接口用途：	查询sku指定月份的囤货数据
method：	POST
接口地址：	listCalendar
输入参数：
key	参数类型	是否必须	参数解释
reserveId	string	是	库存id
month	string	是	2016-06
返回数据：
{
    "success": "true/false //成功/失败",
    "msg": "xxx //返回消息",
    "errorCode": "//",
    "errorMsg": " //",
    "data":
    {
        "month": "xxxx//2016-06",
        "list":
        [
         {
             "avgpriceStr": "xxxx//￥25.25 均价",
             "avgprice": "xxx//25.52",
             "date": "xxxx//2016-06-06",
             "bidcount": "xxx//2均价匹配数",
             "amount": "xxxx//当天囤货库存数",
             "thbuyflag": "xxx//1:出价预购，0：普通预购， 2：固定出价",
         }
         ]
    }
}
备注：
请求参数：
reserveId:xxx//库存id, month:xxx//2016-06,

*/


/*
    {
        "success": true,
        "data": {
            "month": "2017-02",
            "list": [
                     {
                         "amount": 130,
                         "thbuyflag": "1",
                         "avgpriceStr": "￥37.43",
                         "date": "2017-02-27",
                         "bidcount": 58,
                         "avgprice_v2": "37.43",
                         "avgprice": "24.83"
                     }
                     ]
        },
        "errorCode": "",
        "errorMsg": "",
        "msg": ""
    }
 */
+(void)BK_ListCalendar:(BK_Calendar_Callback)CallBack WithReserveId:(NSString *)reserveId andMonth:(NSString *)month{

    kOrderLoading;
    NSDictionary *paramDic = month ? @{@"reserveId" : reserveId, @"month" : month} : @{@"reserveId" : reserveId};
    
    NSString *const ODCalendarURL = @"listCalendar";
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(ODCalendarURL) parameters:paramDic
                                    success:^(id  _Nullable responseObject){
                                        BOOL success = [responseObject[@"success"] boolValue];
                                        if (responseObject == nil || success == NO) {
                                            kOrderDismiss;
                                            kOrderPromptMsg(responseObject[@"msg"]);
                                            return;
                                        }else{
                                            kOrderDismiss;
                                            CallBack(YES, responseObject,nil);
                                        }
                                        
                                    }
                                    failure:^(id  _Nullable responseObject, NSError * _Nullable error){
                                        kOrderDismiss;
                                        NSString *errorMsg;
                                        if (error.code == -1001) {
                                            errorMsg = @"请求超时";
                                        }else if(error.code == 502){
                                            errorMsg = @"服务器开小差了，请稍后再试！";
                                        }else{
                                            errorMsg = @"请求失败";
                                        }
                                        kOrderPromptMsg(errorMsg);
     }];
}

/*
接口名称：	strongbid_v2
接口用途：	查询sku根据日期的匹配囤货数量和价格
method：	POST
接口地址：	strongbid_v2
输入参数：
key	参数类型	是否必须	参数解释
reserveId	string	是	库存id
date	string	是	2016-06-06
返回数据：
{
    "success": "true/false //成功/失败",
    "msg": "xxx //返回消息",
    "errorCode": "//",
    "errorMsg": "//",
    "data":
    {
        "count": "xxxx//匹配的数量",
        "price": "xxx//最强均价",【不含糖赋-】
        "price_v2": "xxx//最强均价",【含糖赋-】

 }
}
备注：
请求参数：
reserveId:xxx//库存id， date:xxx//2016-06-06

*/

/*
    {
        "success": true,
        "data": {
            "count": 63,
            "price": 25.1,【不含糖赋-】
            "price_v2": "37.70"【含糖赋-】
        },
        "errorCode": "",
        "errorMsg": "",
        "msg": ""
    }
*/
+(void)BK_Strongbid:(BK_Calendar_Callback)CallBack WithParamDic:(NSDictionary*)paramDic{
    NSString *const ODStrongestMatchURL = @"strongbid_v2";
    kOrderLoading;
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(ODStrongestMatchURL) parameters:paramDic
                                    success:^(id  _Nullable responseObject)
     {
         
    
         
         BOOL success = [responseObject[@"success"] boolValue];
         if (responseObject == nil || success == NO)
         {
             kOrderDismiss;
             kOrderPromptMsg(responseObject[@"msg"]);
             return;
         }else{
             kOrderDismiss;
             CallBack(YES, responseObject,nil);
         }
     }
                                    failure:^(id  _Nullable responseObject, NSError * _Nullable error)
     {
         kOrderDismiss;
//         NSString *errorMsg;
//         if (error.code == -1001) {
//             errorMsg = @"请求超时";
//         }else if(error.code == 502){
//             errorMsg = @"服务器开小差了，请稍后再试！";
//         }else{
//             errorMsg = @"请求失败";
//         }
//         kOrderPromptMsg(errorMsg);
         CallBack(NO, nil,error);
     }];

    
    
}







+(void)BK_AddShopping:(BK_Calendar_Callback)CallBack WithIsOK:(BOOL)isOK  andShoppingCarParamDic:(NSDictionary*)paramDic  andLimitBuyCount:(NSInteger)limitBuyCount{
    
    NSString *const ODAddBuyCarURL = @"shopping-cart/add";
    if ([RequestManager reachabilityStatus] == RequestReachabilityStatusUnknown || [RequestManager reachabilityStatus] == RequestReachabilityStatusNotReachable) {
        kOrderPromptMsg(@"请检查您的网络");
        return;
    }
    if (!isOK){
        return;
    }
    NSString *paramStr = [paramDic mj_JSONString];
    NSInteger amount = [paramDic[@"goods_amount"] integerValue];
    if (amount > limitBuyCount) {
        NSString *promptMsg = [NSString stringWithFormat:@"最多购买%ld件",(long)limitBuyCount];
        kOrderPromptMsg(promptMsg);
        return;
    }
    
    kOrderLoading;
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(ODAddBuyCarURL) parameters:@{@"data" : paramStr}
                                    success:^(id  _Nullable responseObject){
                                        BOOL success = [responseObject[@"success"] boolValue];
                                        if (success == NO) {
                                            kOrderDismiss;
                                            kOrderPromptMsg(responseObject[@"msg"]);
                                            return;
                                        }
                                        kOrderDismiss;
                                        kOrderSuccessMsg(responseObject[@"msg"]);
                                        CallBack(YES, responseObject,nil);

                                    }failure:^(id  _Nullable responseObject, NSError * _Nullable error){
                                        kOrderDismiss;
                                        NSString *errorMsg;
                                        if (error.code == -1001) {
                                            errorMsg = @"请求超时";
                                        }else if(error.code == 502){
                                            errorMsg = @"服务器开小差了，请稍后再试！";
                                        }else{
                                            errorMsg = @"请求失败";
                                        }
                                        kOrderPromptMsg(errorMsg);
                                    }];
}

/*
 
 
接口名称：	bid
接口用途：	查询sku根据日期出价的匹配囤货数量
method：	POST
接口地址：	bid
输入参数：
key	参数类型	是否必须	参数解释
reserveId	string	是	库存id
date	string	是	2016-06-06
price	float	是	25.25
返回数据：
{
    "success": "true/false //成功/失败",
    "msg": "xxx //返回消息",
    "errorCode": "//",
    "errorMsg": "//",
    "data":
    {
        "count": "xxxx//匹配的数量",
    }
}
备注：
请求参数：
reserveId:xxx//库存id， date:xxx//2016-06-06, price:xxx//25.25

*/


+(void)BK_Bid:(BK_Calendar_Callback)CallBack WithParamDic:(NSDictionary*)paramDic andMatchNum:(NSInteger)matchingNumberIndex{
    NSString *const ODBidURL = @"bid";
     kOrderLoading;
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(ODBidURL) parameters:paramDic
                                    success:^(id  _Nullable responseObject) {
                                        
                                        BOOL success = [responseObject[@"success"] boolValue];
                                        if (responseObject == nil || success == NO) {
                                            kOrderDismiss;
                                            kOrderPromptMsg(responseObject[@"msg"]);
                                            return;
                                        }
                                        
                                        if (matchingNumberIndex == -1) {
                                            kOrderDismiss;
                                            kOrderPromptMsg(@"意外的出价");
                                            return;
                                        }
                                        kOrderDismiss;
                                        CallBack(YES, responseObject,nil);
                                       
                                    }
                                    failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
                                        kOrderDismiss;
                                        NSString *errorMsg;
                                        if (error.code == -1001) {
                                            errorMsg = @"请求超时";
                                        }else if(error.code == 502){
                                            errorMsg = @"服务器开小差了，请稍后再试！";
                                        }else{
                                            errorMsg = @"请求失败";
                                        }
                                        kOrderPromptMsg(errorMsg);
                                    }];
    
}

#pragma mark============下个月月份============
/*
 * 输出格式：@"2016-12"
 */
+ (NSString *)BK_nextMonth:(NSDate *)date{
    
    NSDateFormatter *formatter_date = [[NSDateFormatter alloc] init];
    formatter_date.dateFormat = @"yyyy-MM-dd";
    
    NSString *month;
    NSString *dateStr = [formatter_date stringFromDate:date];
    
    NSInteger monthNumber = [[[dateStr substringToIndex:7] substringWithRange:NSMakeRange(5, 2)] integerValue];
    if (monthNumber == 12)
    {
        NSInteger nextYear = [[dateStr substringToIndex:4] integerValue] + 1;
        month = [NSString stringWithFormat:@"%ld-01",(long)nextYear];
    }
    else{
        month = [[dateStr substringToIndex:5] stringByAppendingString:[NSString stringWithFormat:@"%02ld",(long)(monthNumber + 1)]];
    }
    return month;
}


#pragma mark============判断日期是否在本月============
+ (BOOL)isCurrentMonth:(NSDate *)date{
    NSDateFormatter *formatter_date = [[NSDateFormatter alloc] init];
    formatter_date.dateFormat = @"yyyy-MM-dd";
    
    NSString *dateMonthStr = [[formatter_date stringFromDate:date] substringToIndex:7];
    NSString *currentMonthStr = [[formatter_date stringFromDate:[NSDate date]] substringToIndex:7];
    BOOL isCurrent = [dateMonthStr isEqualToString:currentMonthStr] ? YES : NO;
    return isCurrent;
}


#pragma mark============判断两个日期是否在同一个月============
+ (BOOL)IsInTheSameMonth:(NSDate *)date1 :(NSDate *)date2{
    NSString *month1 = [BK_Calendar_Tool BK_nextMonth:date1];
    NSString *month2 = [BK_Calendar_Tool BK_nextMonth:date2];
    return [month1 isEqualToString:month2];
}

/**
 *  计算字符串里有多少个子串
 *
 *  @param s <#s description#>
 *  @param c <#c description#>
 *
 *  @return <#return value description#>
 */
+(NSInteger)countChar:(NSString *)s cchar:(NSString*)c
{
    NSString *string =s;
    NSString *subString = c;
    NSArray *array = [string componentsSeparatedByString:subString];
    NSInteger count = [array count] - 1;
    
    return count;
}

@end













































